/**   
 * @Title: OrderController.java
 * @Package com.wx.controller
 * @Description: 
 * @author wangxiao
 * @date 2017年11月8日 下午2:53:36
 */
package com.wx.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.eova.common.utils.xx;
import com.eova.interceptor.AuthInterceptor;
import com.eova.interceptor.LoginInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.JMap;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import com.jfinal.template.Engine;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.wx.interceptor.JSSDKInterceptor;
import com.wx.model.User;
import com.wx.model.WxAccount;
import com.wx.model.WxAddInfo;
import com.wx.model.WxOrder;
import com.wx.service.AccountService;
import com.wx.service.OrderService;
import com.wx.service.UserAddService;
import com.wx.validator.AddOrderValidator;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**   
 * @ClassName: OrderController
 * @Description: 
 * @author wangxiao
 * @date 2017年11月8日 下午2:53:36
 */
@Clear({LoginInterceptor.class,AuthInterceptor.class})
public class OrderController extends ApiController{
	static final AccountService accountService = AccountService.me;
	static final UserAddService userAddService = UserAddService.me;
	static final OrderService orderService = OrderService.me;
	static Log log = Log.getLog(OrderController.class);
	@Before(JSSDKInterceptor.class)
	public void toSerBillHis(){
		log.info(AccessTokenApi.getAccessTokenStr());
		User user = getSessionAttr("USER");
		setAttr("USER", user);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		renderTemplate(wx.getSearchUrl());
	}

	@Before(JSSDKInterceptor.class)
	public void serBillHis(){
		User user = getSessionAttr("USER");
		setAttr("USER", user);
		String order_no = getPara("ORDER_NO");
		log.error("===="+order_no);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		String postUrl = wx.getSerHisUrl();
		String userName = xx.getConfig("username","wem1");
		String password = xx.getConfig("password","1");
		Map map = new HashMap<>();
		String response = "";
		log.error("===="+postUrl);
		Map orderMap = new HashMap<>();
		if(wx.getOrderTempKey().contains("A1ORDERRET")){
			Map maps = new HashMap<>();
			maps.put("NO", order_no);
			map.put("JSONDATA", JSONUtil.parse(maps));
			postUrl = postUrl.replace("【NO】", order_no);

			log.error("===="+postUrl);
			response = HttpUtil.get(postUrl);
			log.error("===="+response);
			orderMap = JSONUtil.parseObj(response.substring(1, response.length()-1));
		}else{
			map.put("USER_NAME", userName);
			map.put("PASSWORD", password);
			map.put("billNos", order_no);
			response = HttpUtil.post(postUrl, map);
			orderMap = JSONUtil.parseObj(response);
		}
		if(orderMap.get("returnValue") instanceof List){
			setAttr("HIS", orderMap.get("returnValue"));
			log.error("===="+orderMap.get("returnValue"));
		}else{
		    setAttr("HIS",null);	
		}
		setAttr("BILLNO",order_no);
		renderTemplate(wx.getSearchUrl());
	}
	
	@Before(JSSDKInterceptor.class)
	public void goTest(){
		render("share.jsp");
	}
	
	public void testTemp(){
		User user = getSessionAttr("USER");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
		String time=sdf.format(new Date());
		String json = TemplateData.New()
		.setTouser(user.getOpenId())
		.setTemplate_id("mYmXe1D-gKxr9WQyy9XxTwiaalSt3ItIbJX_JES1XSU")
		.setUrl("http://116.228.202.203:5367/oauth/toOauth?appid=wx3bf19919bcd6fc46")
		.add("first", "您好,你已购买课程成功", "#743A3A")
		.build();
		System.out.println(json);
		ApiResult result = TemplateMsgApi.send(json);
		 System.out.println(result.getJson());
		 renderText("OK");
	}
	@Before(JSSDKInterceptor.class)
	public void toAddOrder(){
		int addid = getParaToInt("addid",-1);
		Map addMap = (Map) getSession().getAttribute("ADDMAP");
		if(addMap!=null){
			
		}else{
			addMap = new HashMap<>();
		}
		if(addid!=-1){
			//有地址库进入时
			WxAddInfo wx = userAddService.getWxAddInfoById(addid);
			addMap.put("receivename", wx.getName());
			addMap.put("receivephone", wx.getMobile());
			addMap.put("receiveadd", wx.getPro()+"||"+wx.getCity()+"||"+wx.getDis()+"^"+wx.getAddress());
			addMap.put("receivecard",wx.getDefine1());
		}else{
			//第一次进入根据用户信息查默认地址
			User user = getSessionAttr("USER");
			WxAddInfo sendInfo = userAddService.getUserDefaultSendAdd(user.getId());
			WxAddInfo receiveInfo = userAddService.getUserDefaultReceiveAdd(user.getId());
			if(receiveInfo!=null){
				addMap.put("receivename", receiveInfo.getName());
				addMap.put("receivephone", receiveInfo.getMobile());
				addMap.put("receivecard", receiveInfo.get("define1", ""));
				addMap.put("receiveadd", receiveInfo.getPro()+"||"+receiveInfo.getCity()+"||"+receiveInfo.getDis()+"^"+receiveInfo.getAddress());
			}
			if(sendInfo!=null){
				addMap.put("sendname", sendInfo.getName());
				addMap.put("sendphone", sendInfo.getMobile());
				addMap.put("sendcard", sendInfo.get("define1", ""));
				addMap.put("sendadd", sendInfo.getPro()+"||"+sendInfo.getCity()+"||"+sendInfo.getDis()+"^"+sendInfo.getAddress());
			}
		}
		getSession().putValue("ADDMAP", addMap);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		renderTemplate(wx.getUrlPath());
	}
	

	public void toUserAdd(){
		//获取地址库信息
		//记录用户已输入的寄件 收件地址
		String sendname = getPara("sendname");
		String sendphone = getPara("sendphone");
		String receivename = getPara("receivename");
		String receivephone = getPara("receivephone");
		String receiveadd = getPara("receiveadd");
		String sendadd = getPara("sendadd");
		String sendcard = getPara("sendcard");
		String receivecard = getPara("receivecard");
		Map addMap = new HashMap<>();
		addMap.put("sendname", sendname);
		addMap.put("sendphone", sendphone);
		addMap.put("receivename", receivename);
		addMap.put("receivephone", receivephone);
		addMap.put("receiveadd", receiveadd);
		addMap.put("sendadd", sendadd);
		addMap.put("sendcard", sendcard);
		addMap.put("receivecard", receivecard);
		getSession().putValue("ADDMAP", addMap);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		User user = getSessionAttr("USER");
		List<WxAddInfo> wxList = userAddService.getAllAddInfoByUserId(user.getId());
		setAttr("WXADDLIST", wxList);
		renderTemplate(wx.getUserAddUrl());
	}
	public void toUserAdd2(){
		//获取地址库信息
		//记录用户已输入的寄件 收件地址
		WxAccount wx = getSessionAttr("WXACCOUNT");
		User user = getSessionAttr("USER");
		List<WxAddInfo> wxList = userAddService.getAllAddInfoByUserId(user.getId());
		setAttr("WXADDLIST", wxList);
		renderTemplate(wx.getUserAddUrl());
	}
	public void toEditUserAdd(){
		//获取地址库信息
		String sendname = getPara("sendname");
		String sendphone = getPara("sendphone");
		String receivename = getPara("receivename");
		String receivephone = getPara("receivephone");
		String receiveadd = getPara("receiveadd");
		String sendadd = getPara("sendadd");
		String sendcard = getPara("sendcard");
		String receivecard = getPara("receivecard");
		String state = getPara("state");
		if("3".equals(state)){
			int addid = getParaToInt("addid");
			WxAddInfo wx = userAddService.getWxAddInfoById(addid);
			receivename = wx.getName();
			receivephone = wx.getMobile();
			if(StrUtil.isEmpty(wx.getDefine1())){
				receivecard= "";
			}else{
				receivecard = wx.getDefine1();
			}
			receiveadd = wx.getPro()+" "+wx.getCity()+" "+wx.getDis()+"^"+wx.getAddress();
			setAttr("addid", addid);
		}
		Map addMap = new HashMap<>();
		addMap.put("sendname", sendname);
		addMap.put("sendphone", sendphone);
		addMap.put("receivename", receivename);
		addMap.put("receivephone", receivephone);
		addMap.put("receiveadd", receiveadd);
		addMap.put("sendadd", sendadd);
		addMap.put("sendcard", sendcard);
		addMap.put("receivecard", receivecard);
		getSession().putValue("ADDMAP", addMap);
		
		setAttr("sendname", sendname);
		setAttr("sendphone", sendphone);
		setAttr("sendadd", sendadd);
		setAttr("sendcard", sendcard);
		setAttr("receivephone", receivephone);
		setAttr("receivename", receivename);
		setAttr("receiveadd", receiveadd);
		setAttr("receivecard", receivecard);
		setAttr("state", state);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		if("9".equals(state)){
			renderTemplate("/wx/xieyi.html");
		}else{
			renderTemplate(wx.getAddEditUrl());
		}
		
	}
	public void deleteAdd(){
		int addid = getParaToInt("addid");
		WxAddInfo wx = userAddService.getWxAddInfoById(addid);
		wx.delete();
		toUserAdd2();
	}
	public void setDefaultAdd(){
		int addid = getParaToInt("addid");
		User user = getSessionAttr("USER");
		userAddService.setDefaultAdd(addid, user.getId());
		toUserAdd2();
	}
	@Before(JSSDKInterceptor.class)
	public void editAdd(){
//		//获取地址库信息
		String state = getPara("state");
//		String sendname = getPara("sendname");
//		String sendphone = getPara("sendphone");
//		String receivename = getPara("receivename");
//		String receivephone = getPara("receivephone");
//		String receiveadd = getPara("receiveadd");
//		String sendadd = getPara("sendadd");
		String name = getPara("name");
		String mobile = getPara("mobile");
		String address = getPara("address");
		String pro_city_dis = getPara("pro_city_dis");
		String card = getPara("card");
		Map addMap = (Map) getSession().getAttribute("ADDMAP");
		if(addMap==null){
			addMap = new HashMap<>();
		}
		if("3".equals(state)){
			//修改地址库时
			int addid = getParaToInt("addid");
			WxAddInfo wx = userAddService.getWxAddInfoById(addid);
			wx.setName(name);
			wx.setMobile(mobile);
			wx.setAddress(address);
			wx.setDefine1(card);
			String[] pcd = pro_city_dis.split("\\|\\|");
			//解析地址
			if(pcd.length>0){
				for(int i=0;i<pcd.length;i++){
					if(i==0){
						wx.setPro(pcd[i]);
					}else if(i==1){
						wx.setCity(pcd[i]);
					}else if(i==2){
						wx.setDis(pcd[i]);
						break;
					}
				}
			}
			wx.update();
			addMap.put("receivename", wx.getName());
			addMap.put("receivephone", wx.getMobile());
			addMap.put("receivecard", wx.getDefine1());
			addMap.put("receiveadd", wx.getPro()+" "+wx.getCity()+" "+wx.getDis()+"^"+wx.getAddress());
			toUserAdd2();
			return;
		}else{
			if("0".equals(state)){
				addMap.put("sendname", name);
				addMap.put("sendcard", card);
				addMap.put("sendphone", mobile);
				addMap.put("sendadd", pro_city_dis +"^"+address);
				String isdefault = getPara("isdefault");
				if("on".equals(isdefault)){
					//保存成默认寄件地址
					User user = getSessionAttr("USER");
					//判断寄件地址是否改变
					WxAddInfo sendAdd = userAddService.getUserDefaultSendAdd(user.getId());
					if(sendAdd==null||(!address.equals(sendAdd.getAddress())||!mobile.equals(sendAdd.getMobile())||!name.equals(sendAdd.getName()))){
						WxAddInfo wx = new WxAddInfo();
						String[] pcd = pro_city_dis.split("\\|\\|");
						wx.setAddress(address);
						wx.setCreateDate(new Date());
						wx.setIsdefault("1");
						wx.setMobile(mobile);
						wx.setName(name);
						wx.setDefine1(card);
						wx.setType("2");
						wx.setUserId(user.getId());
						//解析地址
						if(pcd.length>0){
							for(int i=0;i<pcd.length;i++){
								if(i==0){
									wx.setPro(pcd[i]);
								}else if(i==1){
									wx.setCity(pcd[i]);
								}else if(i==2){
									wx.setDis(pcd[i]);
									break;
								}
							}
						}
						userAddService.setDefaultSendAdd(wx, user);
					}
				}
			}else if("1".equals(state)){
				addMap.put("receivename", name);
				addMap.put("receivephone", mobile);
				addMap.put("receivecard", card);
				addMap.put("receiveadd", pro_city_dis +"^"+address);
			}else if("2".equals(state)){
				//添加地址库
				User user = getSessionAttr("USER");
				WxAddInfo wx = new WxAddInfo();
				String[] pcd = pro_city_dis.split("\\|\\|");
				wx.setAddress(address);
				wx.setCreateDate(new Date());
				wx.setMobile(mobile);
				wx.setName(name);
				wx.setDefine1(card);
				wx.setType("1");
				wx.setUserId(user.getId());
				//解析地址
				if(pcd.length>0){
					for(int i=0;i<pcd.length;i++){
						if(i==0){
							wx.setPro(pcd[i]);
						}else if(i==1){
							wx.setCity(pcd[i]);
						}else if(i==2){
							wx.setDis(pcd[i]);
							break;
						}
					}
				}
				wx.save();
				toUserAdd2();
				return;
			}
		}
		getSession().putValue("ADDMAP", addMap);
		setAttr("state", state);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		renderTemplate(wx.getUrlPath());
	}
	/**
	 * 
	 * @throws UnsupportedEncodingException 
	 * @Title: addOrder
	 * @Description:下单
	 */
	@Before(AddOrderValidator.class)
	public void addOrder() throws UnsupportedEncodingException{
		//获取请求参数
		WxAccount wx = getSessionAttr("WXACCOUNT");
		User user = getSessionAttr("USER");
		//获取省市区
		WxOrder order =getModel(WxOrder.class);
		order.setOrderNo("WO"+DateUtil.date().getDate()+RandomUtil.randomNumbers(9));
		order.setAppid(wx.getAppid());
		order.setUserid(user.getId());
		order.setCreateTime(new Date());
		order.setStatus("0");
		String str = this.getTempMess(order, wx.getOrderTempKey());
		Map paramMap = new HashMap<>();
//		paramMap.put("Constant_id", "createOrder");
		if("wxed61288ed3a45133".equals(wx.getAppid())||"wx3f8913eb9dd15240".equals(wx.getAppid())){
			paramMap.put("content", str);
			paramMap.put("callback", "");
    	}else{
    		paramMap.put("JSONDATA", URLEncoder.encode(str, "utf-8"));
    	}
		String response = HttpUtil.post(wx.getAddOrderUrl(), paramMap);
		Map result = new HashMap<>();
		if("wxed61288ed3a45133".equals(wx.getAppid())||"wx3f8913eb9dd15240".equals(wx.getAppid())||"wx3a61fdeeb89ed828".equals(wx.getAppid())){
			log.info(response);
			result = JSONUtil.parseObj(response.substring(1, response.length()-1));
		}else{
			result = JSONUtil.parseObj(response);
		}
		
		if("SUCCESS".equals(result.get("returnType"))){
			order.setOrderNo((String)result.get("returnValue"));
			order.save();
			renderJson(Ret.ok("ORDERNO", order.getOrderNo()));
		}else{
			renderJson(Ret.fail("ERRMESSAGE", result.get("returnValue")));
		}
	}
	
	public String getTempMess(Object paramMap,String key) {
		//根据参数获取对应模板
		JMap data = JMap.create();
		data.set("data", paramMap);
		Engine.use().setBaseTemplatePath(PathKit.getRootClassPath());
		String str="";
		try{
			str =Engine.use().getTemplate(key).renderToString(data);
		}catch (Exception e) {
			// TODO: handle exception
			str = "ERR";
			throw e;
		}finally{
			return str;
		}
	}
	
	public void toUserOrderList(){
		WxAccount wx = getSessionAttr("WXACCOUNT");
		User user = getSessionAttr("USER");
		List<WxOrder> wxList = orderService.getAllOrderByUser(user.getId(), wx.getAppid());
		setAttr("WXLIST", wxList);
		renderTemplate("/wx/user_order_list.html");
	}
}